package com.dayi.activity.chatroom;

import android.content.Intent;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.activity.chatroom.childfragment.TeacherFirstFragment;
import com.dayi.activity.chatroom.childfragment.TeacherSecondFragment;
import com.dayi.bean.AnswerDetail;
import com.dayi.bean.UploadImage;
import com.dayi.bean.UploadVoice;
import com.dayi.utils.ReportTeacherPopupUtils;
import com.dayi.utils.pop.RecordVoicePopupUtils;
import com.dayi.view.CommonSoundItemView;
import com.google.android.material.tabs.TabLayout;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.file.FileUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.utls.picture_select.PhotoUtil;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.lib.view.navigationbar.NomalNavigationBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterPathUtils.Dayi_RoomStudent)
public class StudentRoomActivity extends BaseAppActivity {

    private static int TYPE_SEND_STUDENT = 1;

    @BindView(R2.id.iv_room_voice)
    ImageView ivRoomVoice;
    @BindView(R2.id.iv_room_message)
    AppCompatEditText etRoomMessage;

    @BindView(R2.id.lin_room_addimg)
    LinearLayout linRoomAddimg;
    @BindView(R2.id.lin_room_report)
    LinearLayout linRoomReport;
    @BindView(R2.id.lin_room_menu)
    LinearLayout linRoomMenu;

    @BindView(R2.id.lin_send)
    LinearLayout linSend;//发送按钮
    @BindView(R2.id.fr_more)
    FrameLayout frMore;
    @BindView(R2.id.iv_room_more)
    ImageView ivRoomMore;

    @BindView(R2.id.tl_item)
    TabLayout tlItem;
    @BindView(R2.id.vp_fragment)
    ViewPager vpFragment;

    TeacherFirstFragment firstFragment;
    TeacherSecondFragment secondFragment;

    private List<Fragment> fglist;
    MyAdapter myAdapter;

    private RecordVoicePopupUtils recordVoicePopupUtils;

    private Map<String, UploadImage> uploadImageMap = new HashMap<>();
    private Map<String, UploadVoice> uploadVoiceMap = new HashMap<>();

    private final int TYPE_IMAGE = 1;
    private final int TYPE_VOICE = 2;

    @Override
    protected void onCreateView() {

        initTitle();

        initRecodVoiceUtils();

        initFragmentList();

        initTabLayout();

    }

    private void initTabLayout() {

        tlItem.setSelectedTabIndicator(0);

        //ViewPager的适配器
        myAdapter = new MyAdapter(getSupportFragmentManager());
        vpFragment.setAdapter(myAdapter);
        //绑定
        tlItem.setupWithViewPager(vpFragment);

        //设置自定义视图
        for (int i = 0; i < tlItem.getTabCount(); i++) {
            TabLayout.Tab tab = tlItem.getTabAt(i);
            tab.setCustomView(myAdapter.getTabView(i));
        }


        etRoomMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim() != null && !"".equals(s.toString().trim())) {
                    linSend.setVisibility(View.VISIBLE);
                    ivRoomMore.setVisibility(View.GONE);
                } else {
                    linSend.setVisibility(View.GONE);
                    ivRoomMore.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                LogUtil.e("输入结束，输入的数据为" + s.toString().trim());

            }
        });


    }

    private void initFragmentList() {

        firstFragment = new TeacherFirstFragment();
        secondFragment = new TeacherSecondFragment();

        //页面，数据源
        fglist = new ArrayList<>();
        fglist.add(firstFragment);
        fglist.add(secondFragment);

    }

    private void initTitle() {

        NomalNavigationBar navigationBar = new NomalNavigationBar.Builder(this).setTitle("聊天室").builder();

    }


    private void initRecodVoiceUtils() {
        recordVoicePopupUtils = new RecordVoicePopupUtils(this);

        recordVoicePopupUtils.setRecordVoicePopupUtilsListener(new RecordVoicePopupUtils.RecordVoicePopupUtilsListener() {
            @Override
            public void onVoiceIconClick() {

            }

            @Override
            public void onRecordFinish(Uri audioPath, int duration) {
                finishRecordDo(audioPath, duration);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_student_0;
    }


    private void finishRecordDo(Uri audioPath, int duration) {
        String realPath = FileUtils.getRealFilePath(StudentRoomActivity.this, audioPath);

        UploadVoice uploadVoice = uploadVoiceMap.get(realPath);

        if (uploadVoice == null) {
            uploadVoice = new UploadVoice();
        }

        uploadVoice.setDuration(duration);
        uploadVoice.setPath(realPath);
        /**
         * 插入音频UI
         */
        final CommonSoundItemView commonSoundItemView = new CommonSoundItemView(StudentRoomActivity.this);
        commonSoundItemView.setAudioEntity(uploadVoice);
        commonSoundItemView.setCommonSoundItemViewListener(new CommonSoundItemView.CommonSoundItemViewListener() {
            @Override
            public void onDelete(UploadVoice audioEntity) {

                showLog("移除voice：" + audioEntity.getPath());
                uploadVoiceMap.remove(audioEntity.getPath());
            }


        });


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        params.topMargin = DisplayUtil.dip2px(StudentRoomActivity.this, 16);
        commonSoundItemView.setLayoutParams(params);

        //将语音插入到聊天列表中
        //messageAdapter.notifyDataSetChanged();
        //判断当前活跃的事哪一个随便，并刷新对应数据
//        if (firstFragment.getUserVisibleHint()) {
//            firstFragment.updateChatMsg();
//        } else {
//            secondFragment.updateSecondChatMsg();
//        }
        uploadVoice.setView(commonSoundItemView);
        uploadVoiceMap.put(realPath, uploadVoice);

        uploadFile(realPath, TYPE_VOICE);
    }

    @OnClick({R2.id.iv_room_voice, R2.id.iv_room_more, R2.id.lin_send, R2.id.lin_room_addimg, R2.id.lin_room_report})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_room_voice) {

            recordVoicePopupUtils.showVoicePopu(view);
        } else if (i == R.id.iv_room_more) {

            if (linRoomMenu.getVisibility() == View.VISIBLE) {
                linRoomMenu.setVisibility(View.GONE);
            } else if (linRoomMenu.getVisibility() == View.GONE) {
                linRoomMenu.setVisibility(View.VISIBLE);
            }

        } else if (i == R.id.lin_send) {//发送消息按钮

            String text = etRoomMessage.getText().toString().trim();
            if (text.equals("")) {
                showToast("内容不能为空");
            }

            AnswerDetail answerDetail1 = new AnswerDetail();

            AnswerDetail.ObjBean objBean1 = new AnswerDetail.ObjBean();
            objBean1.setIs_check(TYPE_SEND_STUDENT);
            objBean1.setCorrect(text);
            answerDetail1.setObj(objBean1);

            //判断当前活跃的事哪一个碎片，并刷新对应数据
            if (firstFragment.getUserVisibleHint()) {
                firstFragment.updateChatMsg(answerDetail1);
            } else {
                secondFragment.updateSecondChatMsg(answerDetail1);
            }

            linSend.setVisibility(View.GONE);
            ivRoomMore.setVisibility(View.VISIBLE);
            etRoomMessage.setText("");


        } else if (i == R.id.lin_room_addimg) {

            PhotoUtil.normalSelectPictureByCode(StudentRoomActivity.this, new ArrayList<LocalMedia>(), 1, PhotoUtil.ASK_ROOM_STU);

        } else if (i == R.id.lin_room_report) {

            ReportTeacherPopupUtils reportPopupUtils = new ReportTeacherPopupUtils(this);
            reportPopupUtils.showAnswerPopuPopu(view);

        }

    }


    //-----------------------------------------------------------------------------------图片选择回调


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoUtil.ASK_ROOM_STU:

                    // 图片、视频、音频选择结果回调

                    LocalMedia media = PictureSelector.obtainMultipleResult(data).get(0);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //linImage.removeAllViews();
                    if (media.isCompressed()) {

                        final String compressPath = media.getCompressPath();
                        //上传文件
                        uploadFile(compressPath, TYPE_IMAGE);
                    }

                    break;

            }

        }
    }


    private void uploadFile(final String compressPath, final int type) {

        showLog("上传文件路径" + compressPath);

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(this);
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(final String s) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        if (type == TYPE_IMAGE) {

                            if (null == s || null == s || s.length() < 5 || "null".equals(s)) {

                                showToast("图片上传失败，请重新选择图片!");

                            } else {

                                UploadImage uploadImage = uploadImageMap.get(compressPath);

                                if (uploadImage == null) {
                                    uploadImage = new UploadImage();
                                }
                                uploadImage.setUrl(s);
                                uploadImageMap.put(compressPath, uploadImage);

                                AnswerDetail answerDetail1 = new AnswerDetail();

                                AnswerDetail.ObjBean objBean1 = new AnswerDetail.ObjBean();
                                objBean1.setIs_check(TYPE_SEND_STUDENT);
                                objBean1.setCorrect(s);
                                answerDetail1.setObj(objBean1);

                                //判断当前活跃的事哪一个碎片，并刷新对应数据
                                if (firstFragment.getUserVisibleHint()) {
                                    firstFragment.updateChatMsg(answerDetail1);
                                } else {
                                    secondFragment.updateSecondChatMsg(answerDetail1);
                                }

                                showLog("上传图片成功:" + s);

                            }

                        }

                        if (type == TYPE_VOICE) {


                            if (null == s || null == s || "null".equals(s) || s.length() < 5) {

                                showToast("语音上传失败，请重新录入!");

                            } else {

                                UploadVoice uploadVoice = uploadVoiceMap.get(compressPath);

                                if (uploadVoice == null) {
                                    uploadVoice = new UploadVoice();
                                }
                                uploadVoice.setUrl(s);
                                uploadVoice.setPlayUrl(SharedPreferenceManager.getInstance(StudentRoomActivity.this).getUserCache().getQiNiuUrl() + s);
                                uploadVoiceMap.put(compressPath, uploadVoice);

                                //判断当前活跃的事哪一个碎片，并刷新对应数据
//                                if (firstFragment.getUserVisibleHint()) {
//                                    firstFragment.updateChatMsg();
//                                } else {
//                                    secondFragment.updateSecondChatMsg();
//                                }

                                showLog("上传语音成功:" + s);

                            }

                        }

                    }
                });
            }

            @Override
            public void onError(String e) {

                showLog("文件上传失败:" + e);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        if (type == TYPE_IMAGE) {
                            UploadImage uploadImage = uploadImageMap.get(compressPath);
                            uploadVoiceMap.remove(compressPath);
                            showToast("选择图片失败！");


                        }

                        if (type == TYPE_VOICE) {

                            UploadVoice uploadVoice = uploadVoiceMap.get(compressPath);
                            uploadVoiceMap.remove(compressPath);

                            showToast("录制语音失败！");


                        }
                    }
                });

            }
        });
        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(this).getUserCache().getQiNiuToken());

    }


    class MyAdapter extends FragmentPagerAdapter {


        public MyAdapter(FragmentManager fm) {
            super(fm);

        }

        @Override
        public Fragment getItem(int position) {
            return fglist.get(position);
        }

        @Override
        public int getCount() {
            return fglist.size();
        }

        /**
         * 自定义方法，提供自定义Tab
         * <p>
         * position 位置
         * return返回Tab的View
         */
        public View getTabView(int position) {
            View v = LayoutInflater.from(StudentRoomActivity.this).inflate(R.layout.item_tl_teacher, null);
            LinearLayout linBg = v.findViewById(R.id.lin_bg);
            ImageView ivUser = (ImageView) v.findViewById(R.id.iv_teacher);
            TextView tvName = (TextView) v.findViewById(R.id.tv_teacher);
            ImageView ivDot = (ImageView) v.findViewById(R.id.iv_dot);

            if (0 == position) {
                ivDot.setVisibility(View.GONE);
            }

            // mTv_Title.setText(titles[position]);
            //mImg.setImageResource(images[position]);
            //添加一行，设置颜色
            //mTv_Title.setTextColor(mTabLayout.getTabTextColors());//
            return v;
        }
    }


}
